package tcln.gxtx.client.widget.form;

import java.util.List;

import tcln.gxtx.client.utils.collection.GwtCollectionUtils;
import tcln.gxtx.client.widget.form.model.SimpleComboBoxModel;

import com.extjs.gxt.ui.client.store.ListStore;
import com.extjs.gxt.ui.client.widget.form.ComboBox;

/**
 * Abstract class for a combobox field which uses {@link SimpleComboBoxModel} as its model data. The display field is
 * {@link SimpleComboBoxModel#PROPERTY_VALUE}.
 * 
 * @param <M>
 *            Model data of this combobox.
 * @author Truong Chau Lien Ngoc (lienngoc@gmail.com)
 */
public class AbstractComboBox<M extends SimpleComboBoxModel> extends ComboBox<M> {

    /**
     * Constructs this widget with an empty dropdown list.
     */
    public AbstractComboBox() {
        setDisplayField(SimpleComboBoxModel.PROPERTY_VALUE);
        setTriggerAction(TriggerAction.ALL);
        setStore(new ListStore<M>());
    }

    /**
     * Constructs this widget with an initial selectable values.
     * 
     * @param values
     */
    public AbstractComboBox(List<M> values) {
        this();
        setValues(values);
    }

    /**
     * Sets choosable values. Old values are removed beforehand.
     * 
     * @param values
     */
    public void setValues(List<M> values) {
        if (getStore().getCount() > 0) {
            getStore().removeAll();
        }
        if (!GwtCollectionUtils.isEmpty(values)) {
            getStore().add(values);
        }
    }

    /**
     * Deselects all values from current choosing dropdown.
     */
    public void deselectAll() {
        getListView().getSelectionModel().deselectAll();
    }

    @Override
    protected void onWindowResize(int width, int height) {
        // The default implementation will collapse the dropdown on window resize.
        // But we have to disable this behavior otherwise we will get the following exception when clicking
        // on the drop button (exspecially when the listbox is inside a flyout)
        /*
         * java.lang.NullPointerException: null at com.extjs.gxt.ui.client.widget.Layer.sync(Layer.java:406) at
         * com.extjs.gxt.ui.client.widget.Layer.setVisibility(Layer.java:337) at
         * com.extjs.gxt.ui.client.widget.form.ComboBox.restrict(ComboBox.java:1501) at
         * com.extjs.gxt.ui.client.widget.form.ComboBox.expand(ComboBox.java:349) at
         * com.extjs.gxt.ui.client.widget.form.ComboBox.onLoad(ComboBox.java:1255) at
         * com.extjs.gxt.ui.client.widget.form.ComboBox.doQuery(ComboBox.java:318) at
         * com.extjs.gxt.ui.client.widget.form.ComboBox.onTriggerClick(ComboBox.java:1325) at
         * com.extjs.gxt.ui.client.widget.form.TriggerField.onComponentEvent(TriggerField.java:108)
         */
        // super.onWindowResize(width, height);
    }
}
